<template>
  <div class="comment-nav">
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入要bobo的内容，最多为120字" maxlength="120" v-model="msg"></textarea>
    <mt-button size="large" type="primary" @click="postComment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,i) in commentList" :key="i">
        <div
          class="cmt-title"
        >第{{ i+1}}楼&nbsp;&nbsp;用户:{{item.user_name}}&nbsp;&nbsp;发表时间:{{item.add_time | dateFormat("YYYY-MM-DD HH:mm:ss ")}}</div>
        <div class="cmt-body">{{item.content}}</div>
      </div>
    </div>
    <mt-button size="large" type="danger" plain @click="getMore">加载更多</mt-button>
  </div>
</template>
<script>
// 配置全局组件
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      pageIndex: 1, //默认展示第一页的数据,
      commentList: [],
      msg: ""
    };
  },
  created() {
    this.getCommet();
  },
  methods: {
    // 获取评论内容
    getCommet() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then(result => {
          console.log(result);

          this.commentList = this.commentList.concat(result.data.message);
        });
    },
    getMore() {
      this.pageIndex++;
      this.getCommet();
    },
    postComment() {
      // 提交评论内容
      // 校验是否为空内容
      if (this.msg.trim().length === 0) {
        return Toast("评论内容不能为空！");
      }

      // 2.4 全局设置 post 时候表单数据格式组织形式   application/x-www-form-urlencoded
      this.$http
        .post("api/postcomment/" + this.$route.params.id, {
          content: this.msg.trim()
        })
        .then(result => {
          if (result.data.status === 0) {
            //说明后台已经将这条评论放到数据库中了
            // 数据提交成功后,将发送的数据组装成一个消息对象,拼接到当前数据最前面
            // 减少一次http请求
            var cstr = {
              user_name: "匿名反馈",
              // 获取当前的时间戳
              add_time: Date.now(),
              content: this.msg.trim()
            };

            this.commentList.unshift(cstr);
            this.msg = "";
            return Toast("发布评论成功！");
          }
        });
    }
  },
  props: ["id"]
};
</script>
<style lang="scss" scoped>
h3 {
  font-size: 18px;
}
textarea {
  height: 85px;
  font-size: 14px;
  margin: 0;
}
.cmt-list {
  margin: 3px;
  .cmt-item {
    font-size: 12px;
    .cmt-title {
      line-height: 30px;
      background: #ccc;
    }
    .cmt-body {
      line-height: 40px;
      text-indent: 2em;
    }
  }
}
</style>
